<?php
namespace work {

    use app\ctr;
    use C\lib\Sms;
    use C\lib\Oss;
    use C\mod\feedback;
    use C\mod\mod;
    use C\mod\news;
    use C\mod\proute;
    use C\mod\rnews;
    use C\mod\siginIn;
    use C\mod\worker;
    use C\mod\workerType;
    use C\mod\location;
    use C\mod\pieceState;
    use C\mod\areaWorker;
    use C\mod\workerd;
    use C\mod\area;
    use C\mod\orderPiece;
    use C\mod\city;
    use C\mod\site;
    use C\mod\sms_routing;
    use C\mod\express;
    use C\lib\Db;
    use C\lib\Text;
    use C\mod\wprice;
    use C\mod\order;
    use C\mod\code;
    use C\mod\voucher;

    class user extends ctr {

        // --- 注册 ---

        public function sign(){

            if($post=$this->getAesPost()) {
                $salt = rand(1000, 9999);

                if (Text::isPhone($post['phone'])) {
                } else {
                    $this->writeAesJson(0, '请输入十一位手机号',1);
                    exit;
                }

                if(worker::get(['phone' => $post['phone']])){
                    $this->writeAesJson(0, '此手机号已经注册',1);
                    exit;
                }

                $time=sms_routing::get(['phone' => $post['phone'],'state' => 0],['id', 'DESC']);

                // --- 验证码在十分钟内有效 ---
                if($time->time_add >= $_SERVER['REQUEST_TIME']-600 && !empty($time)){
                    if($time->code == $post['code']){
                    } else {
                        $this->writeAesJson(0, '验证码错误，请重新输入',1);exit;
                    }
                } else {
                    $this->writeAesJson(0, '验证已过期，请再次发送',1);exit;
                }

                if (preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,16}$/', $post['password'])) {
                    $user = new \C\mod\worker();
                    $user->set([
                        'phone' => $post['phone'],
                        'time_add' => $_SERVER['REQUEST_TIME'],
                        'salt' => $salt,
                        'password' => md5($post['password'] . md5($salt))
                    ]);

                    if ($user->create()) {
                        $this->writeAesJson(1,['worker_id'=>$user->id]);

                    } else {
                        $this->writeAesJson(0, '注册失败请重新注册',1);
                    }
                } else
                    $this->writeAesJson(0, '请输入6-16位，必须包含字母和数字', 1);
            }
        }

        // --- 短信验证 ---
        public function send(){

           if($post = $this->getAesPost()) {
               if(Text::isPhone($post['phone'])){
               }  else {
                   $this->writeAesJson(0, '请输入十一位手机号',1);exit;
               }
                if($time=sms_routing::get(['phone' => $post['phone']],['id', 'DESC'])) {
                    if ($time->time_add >= $_SERVER['REQUEST_TIME'] - 60 && !empty($time)) {
                        $this->writeAesJson(0, '验证已发送，请一分钟后再次发送', 1);exit;
                    }
                }

                $code = rand(100000, 999999);
                $worker=new sms_routing();
                $worker->set([
                    'phone' => $post['phone'],
                    'state' => $post['state'],
                    'idphone' => $post['idphone'],
                    'code' => $code,
                    'time_add' => $_SERVER['REQUEST_TIME']
                ]);
                if($worker->create()) {
                    if($post['state'] == 1){
                        $sms=Sms::send('【便递科技】您的修改验证码为:' . $code . '请您妥善保管,十分钟内有效！', $post['phone']);
                    } elseif($post['state'] == 0){
                        $sms = Sms::send('【便递科技】您的注册验证码为:' . $code . '请您妥善保管,十分钟内有效！', $post['phone']);
                    } elseif($post['state'] == 4){
                        $sms = Sms::send('【便递科技】您的验证码为:' . $code . '请您妥善保管,十分钟内有效！', $post['phone']);
                    } else {
                        $this->writeAesJson(0, '缺少state',1);exit;
                    }

                    if($sms) {
                        $this->writeAesJson(1, 1);
                    } else {
                        $this->writeAesJson(0, '发送失败,请重新发送',1);
                    }
                } else {

                    $this->writeAesJson(0, '请重新发送',1);
                }


            }
        }


        // --- 判断登录 ---
        public function isLogined() {
            
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $e = express::getList([]);
                $a = [];
                foreach($e as $c){
                    $a[]= [
                        'id' => $c->id,
                        'name'=>$c->name
                    ];
                }
                 if($w=wprice::get(['worker_id' => $worker->id,'pay_state'=>1])) {
                     $p =$w->price_mortgage;
                 } else{
                    $p ='';
                }

                $verify = '';
                $type = '';
                if ($workerd = workerd::get(['worker_id' => $_SESSION['worker.id'],'verify' =>3])) {
                    $verify = $workerd->verify;
                    $type = $workerd->type;
                }

                $checkDayStr = date('Y-m-d ',time());
                $timeBegin1 = strtotime($checkDayStr."09:00".":00");
                $timeEnd1 = strtotime($checkDayStr."19:00".":00");

                $curr_time = $_SERVER['REQUEST_TIME'];//当前时间
                if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1){
                    if($worker->start_time && $worker->end_time){
                        if($curr_time>=$worker->start_time && $curr_time<=$worker->end_time){
                            $worker_state='0';
                        }else{
                            $worker_state='1';//1接单  0暂停接单
                        }
                    }else{
                        $worker_state='1';
                    }
                }else{
                    $worker_state='0';
                }

                $this->writeAesJson(1, [
                    'verify' => $verify,
                    'type' => $type,
                    'worker_state' => $worker_state,
                    'head_oss' => $worker->head_oss != '' ? STATIC_PATH . $worker->head_oss : '',
                    'kd' => $a,
                    'price' =>$p
                ], 1);

            }
        }

        // --- 登录 ---
        public function login() {

            if($post = $this->getAesPost()) {
                $e = express::getList([]);
                $a = [];
                foreach($e as $c){
                    $a[]= [
                        'id' => $c->id,
                        'name'=>$c->name
                    ];
                }

                if(isset($post['phone'])) {
                    if (isset($post['password'])) {
                        if ($worker = worker::get(['phone' => trim($post['phone'])])) {
                            $pwd = md5($post['password'] . md5($worker->salt));
                            if ($worker->password == $pwd) {
                                $_SESSION['worker.id'] = $worker->id;
                                $verify = '0';
                                $type='';
                                if($workerd = workerd::get(['worker_id' => $_SESSION['worker.id'],'verify' =>3])){
                                    $verify = $workerd->verify;
                                    $type = $workerd->type;
                                }
                                if($w=wprice::get(['worker_id' => $worker->id,'pay_state'=>1])) {
                                    $p =$w->price_mortgage;
                                } else{
                                    $p ='';
                                }

                                //判断用户接单状态

                                $checkDayStr = date('Y-m-d ',time());
                                $timeBegin1 = strtotime($checkDayStr."09:00".":00");
                                $timeEnd1 = strtotime($checkDayStr."19:00".":00");

                                $curr_time = $_SERVER['REQUEST_TIME'];//当前时间
                                if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1){
                                    if($worker->start_time && $worker->end_time){
                                        if($curr_time>=$worker->start_time && $curr_time<=$worker->end_time){
                                            $worker_state='0';
                                        }else{
                                            $worker_state='1';
                                        }
                                    }else{
                                        $worker_state='1';
                                    }
                                }else{
                                    $worker_state='0';
                                }

                                $this->writeAesJson(1, [
                                    'state' => $type,
                                    'verify' => $verify,
                                    'worker_state' => $worker_state,
                                    'head_oss' => $worker->head_oss != '' ? STATIC_PATH.$worker->head_oss : '',
                                    'kd' =>$a,
                                    'price' =>$p
                                ], 1);
                            } else
                                $this->writeAesJson(0, '密码错误，请您核对密码', 1);
                        } else
                            $this->writeAesJson(0, '用户名不存在请先注册！', 1);
                    } else
                        $this->writeAesJson(0, '缺少password', 1);
                } else
                    $this->writeAesJson(0, '缺少phone', 1);
            }
        }


        // --- 修改密码 ---
        public function updatePwd() {

            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $salt = rand(1000, 9999);
                $pwd = trim($post['password']);
                $npwd = trim($post['npassword']);
                $ypwd = md5($pwd . md5($worker->salt));
                if($worker->password == $ypwd) {
                    if (preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,16}$/', $npwd)) {
                        $worker->set([
                            'password' => md5($npwd . md5($salt)),
                            'salt' => $salt,
                        ]);
                        $worker->update();
                        $this->writeAesJson(1, 1);
                    } else
                        $this->writeAesJson(0, '请输入6-16位，必须包含字母和数字', 1);
                } else
                    $this->writeAesJson(0, '原密码密码错误，请您核对密码', 1);
            }
        }


        // --- 忘记密码 ---

        public function forgetpwd(){

            if($post = $this->getAesPost()) {
                $salt = rand(1000, 9999);

                if (Text::isPhone($post['phone'])) {
                } else {
                    $this->writeAesJson(0, '请输入十一位手机号',1);
                    exit;
                }
                if (preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,16}$/', $post['password'])) {

                    if ($worker = worker::get(['phone' => trim($post['phone'])])) {
                        if ($workerd = workerd::get(['worker_id' => $worker->id])) {
                            Text::isIdCard($post['idcard']); // ---  验证身份证 ---
                            if ($workerd->idcard == $post['idcard']) {

                            } else {
                                $this->writeAesJson(0, '身份证号有误', 1);exit;
                            }
                        }

                    } else {
                        $this->writeAesJson(0, '此号还未注册', 1);exit;
                    }

                    $time = sms_routing::get(['phone' => $post['phone'], 'state' => 1], ['id', 'DESC']);

                    // --- 验证码在十分钟内有效 ---
                    if ($time->time_add >= $_SERVER['REQUEST_TIME'] - 600 && !empty($time)) {
                        if ($time->code == $post['code']) {
                        } else {
                            $this->writeAesJson(0, '验证码错误，请重新输入', 1);exit;
                        }
                    } else {
                        $this->writeAesJson(0, '验证已过期，请再次发送', 1);exit;
                    }

                    $worker->set([
                        'salt' => $salt,
                        'password' => md5($post['password'] . md5($salt))
                    ]);

                    if ($worker->update()) {
                        $this->writeAesJson(1, 1);
                    } else {
                        $this->writeAesJson(0, '失败请重新修改', 1);
                    }
                } else
                    $this->writeAesJson(0, '请输入6-16位，必须包含字母和数字', 1);
            }
        }

        // --- 更换手机 ---

        public function updatephone(){

           if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
               if (Text::isPhone($post['phone'])) {
                   if(worker::get(['phone' => $post['phone']])){
                       $this->writeAesJson(0, '此电话已注册', 1);
                       exit;
                   }
                   if ($workerd = workerd::get(['worker_id' => $worker->id])) {
                       if(Text::isIdCard($post['idcard'])) { // ---  验证身份证 ---
                           if ($workerd->idcard == $post['idcard']) {
                                $time = sms_routing::get(['phone' => $post['phone'], 'state' => 4], ['id', 'DESC']);
                                // --- 验证码在十分钟内有效 ---
                                if ($time->time_add >= $_SERVER['REQUEST_TIME'] - 600 && !empty($time)) {
                                    if ($time->code == $post['code']) {
                                        $worker->set([
                                            'phone' => $post['phone']
                                        ]);

                                        if ($worker->update()) {
                                            $workerd->set([
                                                'phone' => $post['phone']
                                            ]);
                                            $workerd->update();
                                            $this->writeAesJson(1, 1);
                                        } else
                                            $this->writeAesJson(0, '失败请重新修改', 1);

                                    } else
                                        $this->writeAesJson(0, '验证码错误，请重新输入', 1);
                                } else
                                    $this->writeAesJson(0, '验证已过期，请再次发送', 1);
                           } else
                               $this->writeAesJson(0, '身份证号有误', 1);
                       }else
                           $this->writeAesJson(0, '身份证号格式有误', 1);
                   } else
                       $this->writeAesJson(0, '请您先认证', 1);
               } else
                   $this->writeAesJson(0, '请输入十一位手机号', 1);

           }
        }



        // --- 获取用户余额 ---

        public function getPrice() {

            if($post = $this->getAesPost()) {

                if($worker = $this->getLogWorker()) {
//                    $dSta=Db::query('select SUM(p.price) as date_price from bd_proute p, bd_wprice w WHERE p.worker_id = w.worker_id AND YEARWEEK(date_format(time_add,\'%Y-%m-%d\')) =date_format(now(),\'%Y-%m-%d\') AND p.worker_id='.$worker->id);
//                    $data[] = $dSta->fetch(\PDO::FETCH_ASSOC);


                    $start_time=strtotime(date('Y-m-d',time()));
                    $end_time=strtotime(date('Y-m-d',time()).' '.'23:59:59');
                    $dSta=Db::query('select SUM(price) as price from bd_proute WHERE time_add>='.$start_time.' AND time_add<='.$end_time.' AND worker_id='.$worker->id.' AND remark != 2 AND remark != 5');
                    $data = $dSta->fetch(\PDO::FETCH_ASSOC);
                    if(empty($data['price'])){
                        $data['date_price']=0;
                    }
//                    if(empty($data[0]['date_price'])){
//                        $data[0]['date_price']=0;
//                    }
                    $price = wprice::get(['worker_id' => $worker->id,'pay_state'=>1]);
                    if($price){
                        $pricea['price'] = $price->price;
                        $pricea['price_mortgage'] = $price->price_mortgage;
                    }else{
                        $pricea['price'] = 0;
                        $pricea['price_mortgage'] = "0.00";
                    }
                }
                $this->writeAesJson(1, [
                    'price' =>  $pricea['price'],
                    'price_mortgage' => $pricea['price_mortgage'],
                    'date_price' => $data['date_price']
                ],1);

            }
        }





        // --- 当前工作人员的个人信息 ---
        public function getInfo() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

                $workerd = [];
                $workerT = workerd::get(['worker_id' => $worker->id,'verify' =>3]);
                if($workerT) {
                    $workerd[] = [
                        'phone' => $worker->phone,
                        'realname' => $workerT->realname,
                        'idcard' => $workerT->idcard,
                        'subsidiary' => $workerT->subsidiary,
                        'contact' => $workerT->contact,
                        'adress' => $workerT->adress,
                        'verify' => $workerT->verify,
                        'sex' => $workerT->sex,
                        'birthdayt' => $workerT->birthdayt,
                        'birthday' => $workerT->birthday != '' ? $workerT->birthday : substr($workerT->idcard , 6 , 8)

                    ];
                    $this->writeAesJson(1, [
                        'workerd' => $workerd
                    ], 1);
                } else {

                    $this->writeAesJson(2,1);
                }


            }
        }


        // --- 修改生日，性别 ---
        public function infoupdate() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

                if(isset($post['sex']) || isset($post['birthdayt'])  || isset($post['birthday'])){
                   $workerT = workerd::get(['worker_id' => $worker->id]);

                    if(isset($post['sex'])){
                        $workerT->set([
                          'sex' =>$post['sex']
                      ]);
                    }
                    if(isset($post['birthdayt'])){
                        $workerT->set([
                            'birthdayt' =>$post['birthdayt']
                        ]);
                    }
                    if(isset($post['birthday'])){
                        $workerT->set([
                            'birthday' =>$post['birthday']
                        ]);
                    }
                    if($workerT->update()) {
                        $this->writeAesJson(1,1);
                    }
                    else
                        $this->writeAesJson(0, '修改失败',1);
                }else
                    $this->writeAesJson(0, '缺少参数',1);

            }
        }

        // --- 修改头像 ---
        public function headupdate() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($post['head_oss'])) {
                    $HandSize = strlen($post['head_oss']);
                    if (strlen($HandSize) <= 2097152) {
                        Oss::connect();
                        do {
                            $oss_hand = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($worker->id . uniqid() . rand(1000, 9999)) . '.jpg';
                        } while (Oss::isExist($oss_hand));
                        Oss::putFile($oss_hand, base64_decode($post['head_oss']));

                        $worker->set([
                            'head_oss' => $oss_hand
                    ]);
                        if ($worker->update()) {
                            $this->writeAesJson(1,['head_oss' => STATIC_PATH.$oss_hand],1);
                        }

                    } else
                        $this->writeAesJson(0, '身份证照只能小于 2M (' . round($HandSize / 1024 / 1024, 2) . 'M)',1);
                } else
                    $this->writeAesJson(0, '缺少head_oss',1);

            }
        }



        // --- 退出登录 ---

        public function logout() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                unset($_SESSION['worker.id']);
//                if(isset($bpost['device'])) {
//                    $worker->set([
//                        'device' => ''
//                    ]);
//                    $worker->update();
//                }
                $this->writeAesJson(1, 1);
            }
        }




        // --- 消息反馈 ---

        public function feedback() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if(isset($post['context'])){

                    $feedback = new feedback();
                    $feedback->set([
                        'user_id' => $worker->id,
                        'context' => $post['context']
                    ]);
                    if($feedback->create()) {
                        $this->writeAesJson(1,1);
                    }else
                        $this->writeAesJson(0, '添加失败',1);
                } else
                     $this->writeAesJson(0, '缺少context',1);
            }
        }

        // --- 上传身份验证 ---

        public function verifyIdCard() {

            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

                $workerd = workerd::get(['worker_id' => $worker->id]);
                if ($workerd) {
                    if ($workerd->verify == '3') {
                        $this->writeAesJson(0, '不能重复认证',1);exit;
                    }

                    if ($workerd->verify == '1') {
                        $this->writeAesJson(0, '认证中',1);exit;
                    }
                }

                if (isset($post['idcard_oss'])) {
                    if (isset($post['idcard_oss_hand'])) {
                        if (isset($post['paper_oss'])) {
                            $idcardFrontSize = isset($post['idcard_oss']) ? strlen($post['idcard_oss']) : false;
                            if ($idcardFrontSize === false || $idcardFrontSize <= 2097152) {
                                $idcardHandSize = strlen($post['idcard_oss_hand']);
                                if (strlen($idcardHandSize) <= 2097152) {
                                    $paper_oss = strlen($post['paper_oss']);
                                    if (strlen($paper_oss) <= 2097152) {
                                        if (Text::isIdCard($post['idcard'])) {
                                            if (isset($post['realname']) && strlen($post['realname']) > 3) {
//                                                if(Text::isPhone($post['phone'])) {
                                                    Oss::connect();
                                                    do {
                                                        $idcard_oss_hand = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($worker->id . uniqid() . rand(1000, 9999)) . '.jpg';
                                                    } while (Oss::isExist($idcard_oss_hand));
                                                    Oss::putFile($idcard_oss_hand, base64_decode($post['idcard_oss_hand']));


                                                    do {
                                                        $idcard_oss = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($worker->id . uniqid() . rand(1000, 9999)) . '.jpg';
                                                    } while (Oss::isExist($idcard_oss));
                                                    Oss::putFile($idcard_oss, base64_decode($post['idcard_oss']));


                                                    do {
                                                        $paper_oss1 = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($worker->id . uniqid() . rand(1000, 9999)) . '.jpg';
                                                    } while (Oss::isExist($paper_oss1));
                                                    Oss::putFile($paper_oss1, base64_decode($post['paper_oss']));



                                                    if ($workerd) {
                                                        $workerd->set([
                                                            'realname' => $post['realname'],
                                                            'idcard' => $post['idcard'],
                                                            'subsidiary' => $post['subsidiary'],
                                                            'contact' => $post['contact'],
                                                            'adress' => $post['adress'],
                                                            'verify' => 1, // 表验证中
                                                            'idcard_oss_hand' => $idcard_oss_hand,
                                                            'idcard_oss' => $idcard_oss,
                                                            'paper_oss' => $paper_oss1,
                                                            'time_verify' => $_SERVER['REQUEST_TIME'],
                                                            'type' => $post['type'],
                                                            'phone' => $worker->phone,
                                                            'worker_id' => $worker->id
                                                        ]);
                                                        if ($workerd->update()) {
                                                            $this->writeAesJson(1,1);exit;
                                                        } else {
                                                            $this->writeAesJson(0, 'update 失败',1);exit;
                                                        }
                                                    } else {

                                                        $workerd = new workerd();
                                                        $workerd->set([
                                                            'realname' => $post['realname'],
                                                            'idcard' => $post['idcard'],
                                                            'subsidiary' => $post['subsidiary'],
                                                            'verify' => 1, // 表验证中
                                                            'contact' => $post['contact'],
                                                            'adress' => $post['adress'],
                                                            'idcard_oss_hand' => $idcard_oss_hand,
                                                            'idcard_oss' => $idcard_oss,
                                                            'paper_oss' => $paper_oss1,
                                                            'time_verify' => $_SERVER['REQUEST_TIME'],
                                                            'type' => $post['type'],
                                                            'phone' => $worker->phone,
                                                            'worker_id' => $worker->id,
                                                            'time_add' => $_SERVER['REQUEST_TIME']
                                                        ]);
                                                        if ($workerd->create()) {
                                                            $this->writeAesJson(1,1);exit;
                                                        } else {
                                                            $this->writeAesJson(0, 'create 失败',1);exit;
                                                        }
                                                    }

//                                                } else
//                                                    $this->writeAesJson(0, '请输入正确的电话',1);
                                            } else
                                                $this->writeAesJson(0, '真实姓名格式错误',1);
                                        } else
                                            $this->writeAesJson(0, '身份证号格式不正确',1);
                                    } else
                                        $this->writeAesJson(0, '证件找只能小于 2M (' . round($paper_oss / 1024 / 1024, 2) . 'M)',1);
                                } else
                                    $this->writeAesJson(0, '身份证手持只能小于 2M (' . round($idcardHandSize / 1024 / 1024, 2) . 'M)',1);
                            } else
                                $this->writeAesJson(0, '身份证照只能小于 2M (' . round($idcardFrontSize / 1024 / 1024, 2) . 'M)',1);
                        } else
                            $this->writeAesJson(0, '请提交证件认证图片',1);
                    } else
                        $this->writeAesJson(0, '请提交手持身份认证图片',1);
                } else
                    $this->writeAesJson(0, '请提交身份认证图片',1);

            }

        }



        // --- 未读消息 ---
        public function newn(){
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                    $xw = 0;
                    $ow = 0;
                    $n = 0;
                    if($oneo = news::getList(['worker_id' => $worker->id, 'state' => 0,'type' =>1])){
                        foreach($oneo as $o){
                            $ow++;
                        }

                    }
                    if($onex = news::getList(['type' =>0])){
                        foreach($onex as $x){
                            $n++;
                            if(rnews::getList(['nid' => $x->id,'worker_id'=>$worker->id])){
                                $xw++;
                            }
                        }
                    }
            $this->writeAesJson(1,[
                'xw' => $n-$xw,
                'ow' => $ow
            ],1);

            }
        }

        // --- 消息列表 ---
        public function newl(){
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if(isset($post['type'])) {
                    $list = [];
                    if($post['type'] == 1){ //订单消息
                        $newo = news::getList(['worker_id' => $worker->id,'type' => 1]);
                        foreach($newo as $o) {
                            $list[] = [
                                'nid' =>$o->id,
                                'title' =>$o->title,
                                'content' =>$o->content,
                                'time' => date('m月d日 H:i:s', $o->time_add),
                                'state' => $o->state
                            ];
                        }
                    }
                    if($post['type'] == 0){ //系统消息
                        $newx = news::getList(['type' =>0]);
                        foreach($newx as $x){
                            if(rnews::getList(['nid' => $x->id,'worker_id'=>$worker->id])){
                                $state = 1;
                            } else {
                                $state = 0;
                            }
                            $list[] = [
                                'nid' =>$x->id,
                                'title' =>$x->title,
                                'content' =>$x->content,
                                'time' => date('m月d日 H:i:s', $x->time_add),
                                'state' => $state
                            ];
                        }
                    }

                $this->writeAesJson(1,[
                    'list'=>$list
                ],1);

                } else
                    $this->writeAesJson(0,'缺少type',1);

            }
        }

        // --- 未读消息读取 ---
        public function rnew() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {


                if(isset($post['type'])) {
                    if(isset($post['nid'])) {
                        if ($post['type'] == 1) { //订单消息
                            $newo = news::get(['id' => $post['nid'],'worker_id' => $worker->id, 'type' => 1]);
                            if($newo->state == 0){
                                $newo->set([
                                    'state' => 1
                                ]);
                                $newo->update();
                                $this->writeAesJson(1, 1);
                            } else
                                $this->writeAesJson(1, 1);
                        }
                        if ($post['type'] == 0) { //系统消息
                            if(rnews::getList(['nid' =>$post['nid'] ,'worker_id'=>$worker->id])){
                                $this->writeAesJson(1, 1);
                            } else {
                                $or = new rnews();
                                $or->set([
                                    'worker_id' =>$worker->id,
                                    'nid' => $post['nid'],
                                    'time_add' => $_SERVER['REQUEST_TIME']
                                ]);
                                $or->create();
                                $this->writeAesJson(1, 1);
                            }
                        }
                    } else
                        $this->writeAesJson(0,'缺少nid',1);
                } else
                    $this->writeAesJson(0,'缺少type',1);
            }
        }

        // --- 定时定位 ---
        public function location() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $lat = $post['lat'];
                $lng = $post['lng'];
                if(empty($lat)){
                    $this->writeAesJson(0,'缺少经纬度参数!',1);exit();
                }else{
                    $lat = trim($post['lat']+0);
                }

                if(empty($lng)){
                    $this->writeAesJson(0,'缺少经纬度参数!',1);exit;
                }else{
                    $lng = trim($post['lng']+0);
                }

                $time = $_SERVER['REQUEST_TIME'] - $worker->time_update;
                $list= [];
                //--- 判断操作是否小于半分钟 ---
                if($time > 20) {
                    $worker->set([
                        'lat' => $lat,
                        'lng' => $lng,
                        'time_update' => $_SERVER['REQUEST_TIME']
                    ]);
                    $worker->update();
                }
                //是否处于接单状态
                $checkDayStr = date('Y-m-d ',time());
                $timeBegin1 = strtotime($checkDayStr."09:00".":00");
                $timeEnd1 = strtotime($checkDayStr."19:00".":00");

                $curr_time = $_SERVER['REQUEST_TIME'];//当前时间
                if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1){
                    if($curr_time<=$worker->start_time || $curr_time>=$worker->end_time){
                        //获取2公里内的所有下单用户
                        $workerd=workerd::get(['worker_id'=>$worker->id]);
                        $subsidiary=$workerd->subsidiary;
                        if($subsidiary=="顺丰速运"){
                            $res=order::scope($lat,$lng,0,1);
                        }elseif($subsidiary=="优速快递"){
                            $res=order::scope($lat,$lng,0,3);
                        }elseif ($subsidiary=="德邦物流"){
                            $res=order::scope($lat,$lng,0,4);
                        }elseif ($subsidiary=="百世物流"){
                            $res=order::scope($lat,$lng,0,5);
                        }elseif ($subsidiary=="中通快递"){
                            $res=order::scope($lat,$lng,0,2);
                        }elseif ($subsidiary=="申通快递"){
                            $res=order::scope($lat,$lng,0,2);
                        }elseif ($subsidiary=="圆通快递"){
                            $res=order::scope($lat,$lng,0,2);
                        }elseif ($subsidiary=="韵达快递"){
                            $res=order::scope($lat,$lng,0,2);
                        }

                        if($res){
                            $list=$res;
                        }
                    }
                }
                $this->writeAesJson(1, [
                    'list'=>$list
                ],1);
            }
        }


        /*
         *邮寄员的app显示邮寄的快递  托运显示托运 取快递显示取快递  并且具体到哪个公司
         */
        private function orderList($ptype,$type,$lat,$lng,$distance,$wtype)
        {

            $stype = [];
            if (!empty($ptype)) {
                if ($ptype == 1) {
                    if ($wtype == 1) {
                        $stype = ['顺丰'];
                    }
                    if ($wtype == 2) {
                        $stype = ['中通', '申通', '圆通', '韵达'];
                    }
                    if ($wtype == 3) {
                        $stype = ['优速'];
                    }
                }
                if ($ptype == 2) {
                    //$stype=['百世物流','德邦物流'];
                    if ($wtype == 5) {
                        $stype = ['百世物流'];
                    }
                    if ($wtype == 6) {
                        $stype = ['德邦物流'];
                    }
                }
            }
            // echo 555;//exit;
            //获取用户周围n公里内的快递员(取递员)
            //如果附近有快递员推送 没有则返回0  推送成功返回1 不成功返回0
            $list = worker::scop($lat, $lng, $distance);
        }


        // --- 获取其他人定位 ---
        public function getLocation() {

            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($post['lat']) && isset($post['lng']) && $post['lng'] != '' && $post['lat'] != '') {
                    $workerId = $worker->id;
                    $locations = [];
                    $workerIds = [];
                    $getLocations = worker::scope($post['lat'], $post['lng'], $workerId);

                    foreach ($getLocations as $getLocation) {
                        $locations[] = [
                            'id' => $getLocation->id,
                            'lat' => $getLocation->lat,
                            'lng' => $getLocation->lng,
                            'realname' =>$getLocation->realname,
                            'phone' => $getLocation->phone
                        ];
                        $workerIds[] = $getLocation->id;
                    }

                    $workerTypes = [];
                    if (count($workerIds)>0) {    // by  xuic
                        $type = [0,1,2,3];
                        $workerTs = workerType::getList(['defaults' => 1, ['worker_id', 'in', $workerIds],['type','in',$type]]);
                        foreach ($workerTs as $workerT) {
                            $workerTypes[] = ['id' => $workerT->worker_id, 'type' => $workerT->type];
                        }
                    }

                    $this->writeAesJson(1, [
                        'locations' => $locations,
                        'workertypes' => $workerTypes
                    ], 1);
                } else
                    $this->writeAesJson(0, '缺少经纬度', 1);
            }
        }



        // --- 当前工作人员的历史订单 ---
        public function historyOrder() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($_POST['lastId']) && trim($_POST['lastId']) != '') {
                    $lastId = trim($_POST['lastId'] + 0);
                } else {
                    $lastId = 0;
                }
                if($post['lastId'] == 0) {
                    $lastId = ['id','>',$lastId];
                } else {
                    $lastId = ['id','<',$lastId];
                }
                $orders = [];
                $orderIds = [];
                $orderPieces = [];
                $stateIn = [];
                if($post['state'] == 'sender') {
                    $stateIn[] = [1,2,3,4,5,6];
                } else {
                    $stateIn[] = [7,8,9,10,11];
                }

                $workerOrders = pieceState::getList(['worker_id' => $worker->id,  $lastId, ['state_in','in',$stateIn[0]]], [0, 10], ['id', 'DESC']);

                foreach ($workerOrders as $workerOrder) {
                    $orders[] = [
                        'id' => $workerOrder->id,
                        'pieceId' => $workerOrder->piece_id,
                        'stateIn' => $workerOrder->state_in,
                        'timeAdd' => $workerOrder->time_add
                    ];
                    $orderIds[] = $workerOrder->piece_id;
                }
                if(count($orderIds) > 0) {
                    $orderPs = orderPiece::getList([['id', 'in', $orderIds]]);
                    foreach ($orderPs as $orderP) {
                        $orderPieces[] = [
                            'pieceId' => $orderP->id,
                            'pieceCode' => $orderP->piece_code,
                            'name' => $orderP->name_recipient,
                            'phone' => $orderP->phone_recipient,
                            'address' => $orderP->address_recipient,
                            'time' => date('m月d日 H:i:s', $orderP->time_add)
                        ];
                    }
                }
                $this->writeAesJson(1, [
                    'historyOrders' => $orders,
                    'pieceCodes' => $orderPieces
                ], 1);
            }
        }

        // --- 当前用户签到 ---
        public function siginIn() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                $sigin = siginIn::getList(['worker_id' => $worker->id],[0, 1], ['id', 'DESC']);

                $time = isset($sigin[0]) ? $sigin[0]->time_add : false;

                if ( !$time || date('Y-m-d') != date('Y-m-d',$time)) {
                    $areaIds = [];
                    $lat = trim($post['lat'] + 0);
                    $lng = trim($post['lng'] + 0);
                    if ($areas = area::scope($lat, $lng)) {
                        foreach ($areas as $area) {
                            $areaIds[] = $area->id;
                        }
                        if (areaWorker::getList([['area_id', 'in', $areaIds],'worker_id' => $worker->id])) {
                            $sigin = new siginIn();
                            $sigin->set([
                                'worker_id' => $worker->id,
                                'time_add' => $_SERVER['REQUEST_TIME'],
                                'lat' => $lat,
                                'lng' => $lng
                            ]);
                            $sigin->create();
                            $this->writeAesJson(1, 1);
                        } else
                            $this->writeAesJson(0, '还未进工作区域', 1);
                    } else
                        $this->writeAesJson(0, '签到失败', 1);
                } else
                    $this->writeAesJson(0, '今天已签到', 1);
            }
        }


        // --- 历史订单搜索 ---
        public function historyOrderS() {
            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
                if (isset($post['lastId']) && trim($post['lastId']) != '') {
                    $lastId = trim($post['lastId'] + 0);
                } else {
                    $lastId = 0;
                }
                if($post['lastId'] == 0) {
                    $lastId = "id > ".$lastId;
                } else {
                    $lastId = "id < ".$lastId;
                }
                $orders = [];
                $orderIds = [];
                $orderPieces = [];
                if(isset($post['timeStart']) && $post['timeStart'] != '') {
                    $timeStart = strtotime("".$post['timeStart']."");
                } else {
                    $timeStart = 0;
                }
                if(isset($post['timeEnd']) && $post['timeEnd'] != '') {
                    $timeEnd = strtotime("".$post['timeEnd']."");
                } else {
                    $timeEnd = $_SERVER['REQUEST_TIME'];
                }

                $workerOrders = pieceState::getList(['worker_id' => $worker->id, ['time_add','>',$timeStart], ['time_add','<',$timeEnd]]);
                foreach ($workerOrders as $workerOrder) {
                    $orders[] =$workerOrder->piece_id;
                    $orders = array_unique($orders);
                    $orderIds[] = $workerOrder->piece_id;
                    $orderIds = array_unique($orderIds);
                }

                if(count($orderIds)>0) {
                    $sql = [];
                    if (isset($post['name']) && $post['name'] != '') {
                        $sql[] = "name_recipient like '%' " . "'" . $post['name'] . "'" . " '%' ";
                    }
                    if(isset($post['phone']) && $post['phone'] != '') {
                        $sql[] = "phone_recipient like '%' "."'".$post['phone']."'"." '%' ";
                    }
                    if(isset($post['address']) && $post['address'] != '') {
                        $sql[] = "address_recipient like '%' "."'".$post['address']."'"." '%' ";
                    }
                    $sqlS= implode(' AND ',$sql);
                    $orderIds= implode(',',$orderIds);
                    $orderPs = orderPiece::search($orderIds,$sqlS,$sql,$lastId);
                    foreach ($orderPs as $orderP) {
                        $orderPieces[] = [
                            'pieceId' => $orderP->id,
                            'pieceCode' => $orderP->piece_code,
                            'name' => $orderP->name_recipient,
                            'phone' => $orderP->phone_recipient,
                            'address' => $orderP->address_recipient,
                            'time' => date('m月d日 H:i:s', $orderP->time_add)
                        ];
                    }
              }

                $this->writeAesJson(1, [
                    'pieceCodes' => $orderPieces
                ], 1);
            }
        }

        /*
         * 修改接单(暂停开始)状态
         */
        public function upState(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){


                if(!isset($post['worker_state'])){
                    $this->writeAesJson(0,'缺少worker_state参数!',1);exit;
                }

                if($post['worker_state'] == 1){  //1工作状态
                    $data['start_time']=$worker->time_add;
                    $data['end_time']=$worker->time_add;
                } else {
                    if(isset($post['start_time']) && isset($post['end_time'])){
                        if($post['start_time']>=$post['end_time']){
                            $this->writeAesJson(0,'开始时间必须小于结束时间',1);exit;
                        }
                    }else{
                        $this->writeAesJson(0,'请提交时间参数',1);exit;
                    }
                    $data['start_time']=$post['start_time'];
                    $data['end_time']=$post['end_time'];

                }

                $worker->set($data);
                if($worker->update()){

                    //判断用户当前的工作状态
                    $checkDayStr = date('Y-m-d ',time());
                    $timeBegin1 = strtotime($checkDayStr."09:00".":00");
                    $timeEnd1 = strtotime($checkDayStr."19:00".":00");

                    $curr_time = $_SERVER['REQUEST_TIME'];//当前时间
                    if($curr_time >= $timeBegin1 && $curr_time <= $timeEnd1){

                        if(isset($post['end_time']) && isset($post['start_time'])){
                            if($curr_time>=$post['start_time'] && $curr_time<=$post['end_time']){
                                $worker_state='0';
                            }else{
                                $worker_state='1';//1接单  0暂停接单
                            }
                        }else{
                            if($curr_time>=$worker->start_time && $curr_time<=$worker->end_time){
                                $worker_state='0';
                            }else{
                                $worker_state='1';//1接单  0暂停接单
                            }
                        }
                    }else{
                        $worker_state='0';
                    }

                    $this->writeAesJson(1,['worker_state'=>$worker_state],1);exit;
                }else{
                    $this->writeAesJson(0,'修改状态失败',1);exit;
                }
            }
        }

        /*
         * 填写邀请码
         */
        public function getVoucher(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){

                if(isset($post['type'])){
                    if($post['type']==1){
                        $wid=code::get(['worker_id'=>$worker->id]);
                        if($wid){
                            $this->writeAesJson(1,['phone'=>$wid->phone],1);exit;
                        }else{
                            $this->writeAesJson(1,['phone'=>''],1);exit;
                        }
                    }
                }
                if(empty($post['content'])){
                    $this->writeAesJson(0,'请填写邀请码!',1);exit;
                }

                //不能填写自己的手机号作为邀请码
                if($worker->phone==$post['content']){
                    $this->writeAesJson(0,'不能填写自己的手机号作为邀请码！',1);exit;
                }
                //查询手机号是否已经注册 没有注册不能填写
                $uphone=worker::get(['phone'=>$_POST['content']]);
                if(!$uphone){
                    $this->writeJson(0,'此手机号不是推荐人！');exit;
                }


                $is_get=code::get(['worker_id'=>$worker->id]);
                if(!$is_get){
                    try {
                        Db::beginTransaction();

                        $code=new code();
                        $code->set([
                            'worker_id'=>$worker->id,
                            'phone'=>$post['content']
                        ]);
                        $addcode=$code->create();
                        $yworker=worker::get(['phone'=>$post['content']]);
                        $wprice=wprice::get(['worker_id'=>$yworker->id]);//用户资产
                        if($wprice){
                            $wprice->set([
                                'worker_id'=>$yworker->id,
                                'price'=>$wprice->price+2
                            ]);
                            $upwprice=$wprice->update();
                        }else{
                            $wprices=new wprice();
                            $wprices->set([
                                'worker_id'=>$yworker->id,
                                'price'=>2
                            ]);
                            $upwprice=$wprices->create();
                        }

                        $proute=new proute();
                        $proute->set([
                            'worker_id'=>$yworker->id,
                            'price'=>2,
                            'pay_type'=>'nb',
                            'pay_state'=>1,
                            'remark'=>1,//奖励是1  惩罚是2 正常客户端收入3
                            'time_add'=>$_SERVER['REQUEST_TIME']
                        ]);
                        $addproute=$proute->create();

                        if ($addcode && $upwprice && $addproute) {
                            Db::commit();
                            $this->writeAesJson(1,1);
                        } else {
                            Db::rollBack();
                            $this->writeAesJson(0,'失败!',1);
                        }
                    } catch (\Exception $e) {
                        Db::rollBack(); // 执行失败，事务回滚
                        $this->writeAesJson(0,'失败!',1);
                    }
                }else{
                    $this->writeAesJson(0,'您已填写过邀请码！',1);
                }
            }
        }
        /*
         * 判断用户是否已经绑定支付宝
         */
        public function isBind(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())) {
                $wprice = wprice::get(['worker_id' => $worker->id]);
                $alipay = '';
                if (!empty($wprice->alipay)) {
                    $alipay = $wprice->alipay;
                }
                $this->writeAesJson(1, [
                    'alipay' => $alipay
                ], 1);

            }
        }
        /*
         * 绑定支付宝
         */
        public function bindAlipay(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){
                if(empty($post['alipay'])){
                    $this->writeAesJson(0,'缺少alipay参数!',1);exit;
                }
                $wprice=wprice::get(['worker_id'=>$worker->id]);
                if($wprice){
                    $wprice->set([
                        'alipay'=>$post['alipay']
                    ]);
                    if($wprice->update()){
                        $this->writeAesJson(1,1);exit;
                    }else{
                        $this->writeAesJson(0,'绑定失败！',1);exit;
                    }
                }else{//资产表里没有数据的时候 插入操作
                    $wprice=new wprice();
                    $wprice->set([
                        'worker_id'=>$worker->id,
                        'alipay'=>$post['alipay']
                    ]);
                    if($wprice->create()){
                        $this->writeAesJson(1,1);exit;
                    }else{
                        $this->writeAesJson(0,'绑定失败！',1);exit;
                    }
                }
            }
        }

        /*
         * 分享页面绑定人数 奖励统计
         */
        public function share(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){

                $data=count(code::getList(['phone'=>$worker->phone]));
                if($data){
                    $price=$data*2;//奖励金额  拉一个人奖励2元
                    $this->writeAesJson(1,[
                        'num'=>$data,
                        'price'=>$price
                    ],1);
                }else{
                    $this->writeAesJson(1,[
                        'num'=>'0',
                        'price'=>'0.00'
                    ],1);
                }
            }
        }

        /*
         * 申请退押金
         */
        public function withdrawals(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){
                $proute=proute::get(['worker_id'=>$worker->id,'remark'=>5,'pay_state'=>1]);
                if($proute){
                    $proute->set([
                        'pay_state'=>2
                    ]);
                    if($proute->update()){
                        $this->writeAesJson(1,1);
                    }else{
                        $this->writeAesJson(0,'申请退押金失败！',1);
                    }
                }else{
                    $this->writeAesJson(0,'您还未充值押金！',1);
                }
            }
        }
        /*
         * 申请提现
         */
        public function withd(){
            if(($post=$this->getAesPost()) && ($worker=$this->getLogWorker())){
                if(empty($post['money'])){
                    $this->writeAesJson(0,'请输入提现金额！');exit;
                }
                $wprice=wprice::get(['worker_id'=>$worker->id,'pay_state'=>1]);
                if($post['money']>$wprice->price_mortgage){
                    if(empty($wprice->alipay)){
                        $this->writeAesJson(0,'请绑定支付宝再申请提现！');
                    }else{
                        $wprice->set([
                            'pay_state'=>3,
                            'money'=>$post['money']
                        ]);
                        if($wprice->update()){
                            $this->writeAesJson(1,1);
                        }else{
                            $this->writeAesJson(0,'申请提现失败！',1);
                        }
                    }
                }else{
                    $this->writeAesJson(0,'提现金额大于收入申请提现失败！',1);
                }
            }
        }

    }
}


